﻿/** Code By Adams Chao
*   NETDB CORP.
*   2013 (C)
**/

var HostUrl = "/HomeDelivery";
//var HostUrl = "";

//Using SSL Path
if (document.location.protocol == 'http:') {
  var href = document.location.href.split('http://');
  var oherf = 'https://' + href[1];
  if (document.location.host == 'mall.evaair.com') {
    document.location = oherf;
  }
}

//加入最愛
function favority(title, url) {  
  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    alert("此功能不支援Chrome瀏覽器.請按Ctrl-D(Command+D for Macs)建立書籤.");
  } else if (window.sidebar) { //FireFox
    window.sidebar.addPanel(title, url, "");
  } else if (window.external || document.all) { //IE
    window.external.AddFavorite(url, title);
  } else if (window.opera) { //Opera 
    var elem = document.createElement('a');
    elem.setAttribute('href', url);
    elem.setAttribute('title', title);
    elem.setAttribute('rel', 'sidebar');
    elem.click();
    //return true;
  }
  else {
    alert("您的瀏覽器不支援此功能!");
    return false;
  }
}


$(document).ready(function () {
  /*限定數量控制項只能輸入數字*/
  $("[id*='txtboxQty']").keydown(function (event) {
    // Allow: backspace, delete, tab, escape, and enter
    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
      // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
      // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
      // let it happen, don't do anything
      return;
    }
    else {
      // Ensure that it is a number and stop the keypress
      if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
        event.preventDefault();
      }
    }
  });

  /*捲動視窗来判斷按钮是否顯示*/
  $(window).scroll(function () {
    if ($(this).scrollTop() > 150) {
      $('.go-to-top').fadeIn(100);
    } else {
      $('.go-to-top').fadeOut(100);
    }
  });

  /*jQuery回頂層*/
  $('.go-to-top').click(function (event) {
    event.preventDefault();
    $('html, body').animate({ scrollTop: 0 }, 500);
  })  

  /*新增商品至購物車*/
  $('.JS-addCart').click(function (e) {
    var qty = $("[id*='txtboxQty']").val();
    if (qty < 1) {      
      $('.popup-content #spanMsg').html("訂購數量不得小於1 !!!");
      lightbox($(".popup-content .message-finish").prop('outerHTML'));      
      return false;
    }

    var b2c_code = $("[id*='lbl_B2C_CODE']").html();
    var smas_code = $("[id*='ddlSpec']").val();
    var catid = $("[id*='HF_ProdCatID']").val();

    var mileage_type = "1"; //預設是現金
    if (catid == "1") {
      //哩上加哩時要知道是選取何種付費方式 1: 現金 2: 自付哩程      
      mileage_type = $("[id*='radio_mileage']:checked").val();
      //alert(mileage_type);
    }

    /*Add by Ajax*/
    //var newItem = $('.list-item:first-child').clone();
    //$('.slide-area').append(newItem);

    //alert($("[id*='lbl_B2C_CODE']").html());
    //alert($("[id*='lbl_ACT_PRICE']").html());
    //alert($("[id*='txtboxQty']").val());
    //alert($("[id*='ddlSpec']").val());
    //alert($("[id*='HF_ProdCatID']").val());

    $.ajax({
      type: "POST",
      url: HostUrl + "/Shopping/AddToCart.aspx/AddProductToCart",
      data: "{'b2c_code': '" + b2c_code
        + "','smas_code': '" + smas_code
        + "','qty': '" + qty
        + "','catid':'" + catid
        + "','product_type':'" + mileage_type + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data, status) {
        if (data.d == '-2') {
          $('.shopping-cart-box').css("display", "none");
          $('.popup-content #spanMsg').html("此規格之商品庫存量不足!!!");
          lightbox($(".popup-content .message-finish").prop('outerHTML'));          
          e.preventDefault();
        }
        else if (data.d != '-1') {
          $('.shopping-cart-box .slide-area').empty();
          MakeCart(data.d);
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        //alert("ERROR : " + JSON.stringify(xhr));
      }
    });

    /*When Ajax complate call this function*/
    $('.shopping-cart-box').fadeIn(300, function () {
      sc = $('.shopping-cart-box .slide-area').height();
      $('html, body').animate({ scrollTop: 0 }, 500);
      $('.listing').animate({ scrollTop: sc }, 1000);
      $('.shopping-cart-box .list-item:last-child').addClass('newest');
      setTimeout(function () {
        $('.list-item .newest').removeClass('newest');
      }, 2000);
    });

  });

  /*取得購物車*/
  $('.JS-GetCart').click(function (e) {
    $.ajax({
      type: "POST",
      url: HostUrl + "/Shopping/AddToCart.aspx/GetCartItems",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data, status) {
        if (data.d != '-1') {
          $('.shopping-cart-box .slide-area').empty();
          MakeCart(data.d);
        }
        else {
          $("[id*='lb_ConfirmOrder']").hide();
          $("[id*='ShowCartList']").hide();
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        //alert("ERROR : " + JSON.stringify(xhr));
      }
    });
  });

  /*新增商品至預選清單*/
  $('.JS-addWish').click(function (e) {
    var qty = "1";
    var b2c_code = $("[id*='lbl_B2C_CODE']").html();
    var smas_code = $("[id*='ddlSpec']").val();
    var catid = $("[id*='HF_ProdCatID']").val();
    var mileage_type = "1"; //預設是現金
    if (catid == "1") {
      //哩上加哩時要知道是選取何種付費方式 1: 現金 2: 自付哩程      
      mileage_type = $("[id*='radio_mileage']:checked").val();      
    }
    /*Add by Ajax*/
    $.ajax({
      type: "POST",
      url: HostUrl + "/Shopping/AddToWishlist.aspx/AddProductToWishlist",
      data: "{'b2c_code': '" + b2c_code
        + "','smas_code': '" + smas_code
        + "','qty': '" + qty
        + "','catid':'" + catid
        + "','product_type':'" + mileage_type + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (data, status) {
        if (data.d != '-1') {
          var result = JSON.parse(data.d);
          var totalCounter = 0;
          $.each(result, function (i, item) {
            totalCounter += 1;
          });
          $("#myWishCounter").text(totalCounter);
          $('.popup-content #spanMsg').html("商品加入預選清單已完成!!!");
          lightbox($(".popup-content .message-finish").prop('outerHTML'));
        }
      },
      error: function (xhr, ajaxOptions, thrownError) {
        //alert("ERROR : " + JSON.stringify(xhr));
      }
    });
  });

  /*商品加入追蹤視窗*/
  $('.JS-AddSave').click(function () {
    lightbox($(".popup-content .save-email").prop('outerHTML'));
  });

  /*商品加入傳送郵件*/
  $('.JS-AddFollow').click(function () {
    lightbox($(".popup-content .follow-email").prop('outerHTML'));
  });

  /*反詐騙視窗*/
  $('.Nolie').click(function () {
    lightbox($(".popup-content .message-165").prop('outerHTML'));
  });

  /*結帳過程限制身分轉換*/
  var currentURL = window.location.href;
  if (currentURL.search('/Orders/') > 0) {
    $(".login-areas").fadeOut(100);
    $(".login-links").fadeOut(100);
  }

});

function MakeCart(data) {
  var result = JSON.parse(data);
  var totalPrice = 0;
  var totalCounter = 0;
  $.each(result, function (i, item) {
    //var content = "index:" + i + "; SMAS_CODE: " + item.SMAS_CODE + "; B2C_CODE: " + item.B2C_CODE;    
    /*目的：組出購物車UI*/
    var divListItem = $("<div>", { "class": "list-item" });

    var link = $("<a>", { "href": HostUrl + "/Products/ProductDetail.aspx?B2C_CODE=" + item.B2C_CODE });
    $("<img>", { "src": item.ImagePath }).appendTo(link);
    link.appendTo(divListItem);

    var divListItemInfo = $("<div>", { "class": "list-item-info" });
    var h5 = $("<H5>");
    $("<a>", { "href": HostUrl + "/Products/ProductDetail.aspx?B2C_CODE=" + item.B2C_CODE }).text(item.ProductName).appendTo(h5);
    h5.appendTo(divListItemInfo);
    if (item.Spec != "") {
      $("<table><tr><th>訂購數量</th><td>" + item.Quantity + "</td></tr><tr><th>價　　格</th><td><strong>$ " + numeral(item.Price).format('0,0') + "</strong></td></tr><tr><th>規　　格</th><td><strong>" + item.Spec + "</strong></td></tr></table>").appendTo(divListItemInfo);
    }
    else {
      $("<table><tr><th>訂購數量</th><td>" + item.Quantity + "</td></tr><tr><th>價　　格</th><td><strong>$ " + numeral(item.Price).format('0,0') + "</strong></td></tr></table>").appendTo(divListItemInfo);
    }
    $("<a>", { "href": "#", "class": "delete", "onclick": "DeleteCartItem(" + item.SMAS_CODE + ");" }).appendTo(divListItemInfo);
    divListItemInfo.appendTo(divListItem);

    divListItem.appendTo($('.shopping-cart-box .slide-area'));
    totalPrice += item.Quantity * item.Price;
    totalCounter += 1;
  });

  $(".toptal-price").text(numeral(totalPrice).format('$ 0,0[.]00'));
  //$(".toptal-price").text("$ " + totalPrice);
  $("#CartCounter").text(totalCounter);
  $("#myCartCounter").text(totalCounter);

  if (totalCounter == 0) {
    $("[id*='lb_ConfirmOrder']").hide();
    $("[id*='ShowCartList']").hide();
  }
  else {
    $("[id*='lb_ConfirmOrder']").show();
    $("[id*='ShowCartList']").show();
  }
}

/*刪除購物車中的項目*/
function DeleteCartItem(smas_code) {
  $.ajax({
    type: "POST",
    url: HostUrl + "/Shopping/AddToCart.aspx/DeleteCartItems",
    data: "{'smas_code': '" + smas_code + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data, status) {
      if (data.d != '-1') {
        $('.slide-area').empty();
        MakeCart(data.d);
      }
    },
    error: function (xhr, ajaxOptions, thrownError) {
      //alert("ERROR : " + JSON.stringify(xhr));
    }
  });
}

/*商品加入追蹤MAIL-Save*/
function SaveProductToMail() {
  var b2c_code = $("[id*='lbl_B2C_CODE']").html();
  var smas_code = $("[id*='ddlSpec']").val();
  var email = $('.lightbox #email-save').val();
  //alert(b2c_code);
  //alert(email);
  if (!validateEmail(email)) {
    $('.lightbox .email-message').html("E-MAIL格式有誤，請輸入正確的E-MAIL資料!");
    return false;
  }
  //Write Mail TO WS
  $.ajax({
    type: "POST",
    url: HostUrl + "/Services/WebService.asmx/SaveFollowMail",
    data: "{'b2c_code': '" + b2c_code
      + "','smas_code':'" + smas_code
      + "','mail_address':'" + email + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data, status) {
      if (data.d != -1) {
        //Mail儲存成功
        alert("E-Mail追蹤商品成功");
      }
      else {
        $('.lightbox .email-message').html("E-MAIL儲存失敗!請聯絡系統管理員!");
        return false;
      }
    },
    error: function (xhr, ajaxOptions, thrownError) {
      //alert("ERROR : " + JSON.stringify(xhr));
    }
  });

  lightboxClose();
  //function lightboxClose() {
  //  $('.lightbox').fadeOut(function () {
  //    $(this).remove();
  //    $('.lightbg').fadeOut(function () {
  //      $(this).remove();
  //    });
  //  });
  //}
}

/*商品加入傳送MAIL-follow*/
function SendProductToMail() {
  var b2c_code = $("[id*='lbl_B2C_CODE']").html();
  var email = $('.lightbox #email-follow').val();
  if (!validateEmail(email)) {
    $('.lightbox .email-message').html("E-MAIL格式有誤，請輸入正確的E-MAIL資料!");
    return false;
  }
  //Call WS To Mail
  $.ajax({
    type: "POST",
    url: HostUrl + "/Services/WebService.asmx/SendProductMail",
    data: "{'b2c_code': '" + b2c_code
      + "','mail_address':'" + email + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data, status) {
      if (data.d != -1) {
        //Mail 傳送成功
        //alert("Mail 傳送成功");
      }
      else {
        $('.lightbox .email-message').html("E-MAIL傳送失敗!請聯絡系統管理員!");
        return false;
      }
    },
    error: function (xhr, ajaxOptions, thrownError) {
      //alert("ERROR : " + JSON.stringify(xhr));
    }
  });

  lightboxClose();
}

/*驗整Mail格式資料*/
function validateEmail($email) {
  //var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  var emailReg = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
  if (!emailReg.test($email)) {
    return false;
  } else {
    return true;
  }
}

function StopBubble(e) {
  if (e && e.stopPropagation) {//非IE 
    e.stopPropagation();
  }
  else {//IE 
    window.event.cancelBubble = true;
  }
}

function lightboxClose() {
  $('.lightbox').fadeOut(function () {
    $(this).remove();
    $('.lightbg').fadeOut(function () {
      $(this).remove();
    });
  });
}

/*身分證格式驗證*/
function CheckTWID(id) {
  //建立字母分數陣列(A~Z)
  var city = new Array(
       1, 10, 19, 28, 37, 46, 55, 64, 39, 73, 82, 2, 11,
      20, 48, 29, 38, 47, 56, 65, 74, 83, 21, 3, 12, 30
  )
  id = id.toUpperCase();
  // 使用「正規表達式」檢驗格式
  if (id.search(/^[A-Z](1|2)\d{8}$/i) == -1) {
    return false;
  } else {
    //將字串分割為陣列
    id = id.split('');
    //計算總分
    var total = city[id[0].charCodeAt(0) - 65];
    for (var i = 1; i <= 8; i++) {
      total += eval(id[i]) * (9 - i);
    }
    //補上檢查碼(最後一碼)
    total += eval(id[9]);
    //檢查比對碼(餘數應為0);
    return ((total % 10 == 0));
  }
}
